<template>
  <div class="container">
    <star-nav-bar />
    <div class="login-content flex-column">
      <div class="login">
        <h2 class="title">{{ title }}</h2>
        <van-form @submit="onSubmit" autocomplete="off" validate-trigger="onSubmit" ref="formRef">
          <van-cell-group inset>
            <van-field name="phone" v-model="phone" placeholder="请输入手机号" :rules="mobileRules">
              <template #label v-if="type === 'code'">
                <van-button size="small" type="default">+86</van-button>
              </template>
            </van-field>
            <van-field v-if="type === 'code'" name="code" v-model="code" center clearable placeholder="请输入短信验证码">
              <template #button>
                <van-button size="small" type="primary" :disabled="isCountingDown" @click="codeHandle(phone)">
                  {{ countdownText }}
                </van-button>
              </template>
            </van-field>
            <van-field v-else v-model="password" name="password" type="password" placeholder="请输入密码"
              :rules="passwordRules" />
          </van-cell-group>
          <div class="btn-box">
            <van-button round block type="primary" native-type="submit" :disabled="isButtonDisabled">
              {{ submitButtonText }}
            </van-button>
            <div class="btn" v-if="type === 'pwd'">
              <span @click="type = 'code'">快速登录</span>
              <span @click="type = 'register'">注册</span>
            </div>
            <div class="btn" v-if="type === 'code'">
              <span @click="type = 'pwd'">账号登录</span>
              <span @click="type = 'register'">注册</span>
            </div>
            <div class="btn" v-if="type === 'register'">
              <span @click="type = 'pwd'">账号登录</span>
              <span @click="type = 'code'">快速登录</span>
            </div>
          </div>
        </van-form>
      </div>
    </div>
    <div class="agreement">
      <van-checkbox v-model="agree">
        <span> 请阅读并同意星轻食的<a href="">《用户登录协议》</a></span>
      </van-checkbox>
    </div>
  </div>
  <van-popup v-model:show="showAgree" class="popup-wrapper">
    <div class="popup-content">
      <h2 class="popup-title">用户登录协议</h2>
      <div class="agreement">请阅读并同意星轻食的<a href="">《用户登录协议》</a></div>
      <div class="popup-footer">
        <van-button size="small" type="primary" @click="agreeHandle">同意并登录</van-button>
        <van-button size="small" type="default" @click="showAgree = false">不同意</van-button>
      </div>
    </div>
  </van-popup>
</template>
<script setup lang="ts">
import { codeLoginAPI, loginAPI, registerAPI } from '@/api/user'
import { useUserStore } from '@/stores'
import { mobileRules, passwordRules } from '@/utils/rules'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const imageUrl = ref('')
import('/images/logo.png').then((module) => {
  imageUrl.value = module.default
})
const router = useRouter()
const route = useRoute()
// 用户store
const userStore = useUserStore()
const phone = ref('')
const password = ref('')
// 登录方式
type AllowedTypes = 'pwd' | 'code' | 'register'
const type = ref<AllowedTypes>('pwd')
// 是否同意协议
const agree = ref(false)
// 同意协议弹窗
const showAgree = ref(false)
// 标题
const title = computed(() => {
  if (type.value === 'pwd') return '账号登录'
  if (type.value === 'code') return '手机登录/注册'
  if (type.value === 'register') return '账号注册'
  return ''
})
// 按钮标题
const submitButtonText = computed(() => {
  if (type.value === 'pwd') return '登录'
  if (type.value === 'code') return '登录'
  if (type.value === 'register') return '注册'
  return ''
})

// 如果密码和手机号都为空，则禁用登录按钮
const isButtonDisabled = computed(() => {
  if (type.value === 'pwd') return phone.value === '' || password.value === ''
  if (type.value === 'code') return phone.value === '' || code.value === ''
})

// 协议弹窗
const agreeHandle = async () => {
  agree.value = true
  if (type.value === 'pwd') await login()
  if (type.value === 'code') await codeLogin()
  if (type.value === 'register') await register()
}

// 登录请求
const login = async () => {
  const params = {
    phone: phone.value,
    password: password.value,
  }
  try {
    const { data } = await loginAPI(params)
    userStore.setUser(data)
    localStorage.setItem('token', data.token)
    router.push((route.query.returnUrl as string) || '/my')
    // showSuccessToast('登录成功')
  } catch (error) {
    console.log(error)
  }
  // 关闭弹窗
  showAgree.value = false
}
// 注册请求
const register = async () => {
  const params = {
    phone: phone.value,
    password: password.value,
  }
  try {
    await registerAPI(params)
    type.value = 'pwd'
  } catch (error) {
    console.log(error)
  }
}
// 验证码登录
const codeLogin = async () => {
  try {
    const parms = {
      phone: phone.value,
      code: code.value,
    }
    const { data } = await codeLoginAPI(parms)
    userStore.setUser(data)
    localStorage.setItem('token', data.token)
    router.push((route.query.returnUrl as string) || '/my')
  } catch (error) {
    console.log(error);
  }
  // 关闭弹窗
  showAgree.value = false
}

// 发送验证码
import useSendCode from './useSendCode'
const { formRef, code, isCountingDown, countdownText, codeHandle } = useSendCode()

// 登录/注册表单提交
const onSubmit = async () => {
  await formRef.value?.validate()
  if (type.value === 'register') {
    register()
    return
  } else if (type.value === 'pwd') {
    if (!agree.value) {
      showAgree.value = true
    } else {
      login()
      return
    }
  } else if (type.value === 'code') {
    console.log(type.value);
    if (!agree.value) {
      showAgree.value = true
    } else {
      codeLogin()
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep() {
  .van-field__label {
    width: auto;
  }
}

.van-form {
  width: 100vw;
}

.login-content {
  margin-top: 46px;
  flex: 1;
}

.login {
  display: flex;
  flex-direction: column;
  align-items: center;

  .title {
    font-size: 20px;
    margin-bottom: 50px;
  }
}

.btn-box {
  margin: 20px;
  border-radius: var(--van-radius-sm);

  .btn {
    font-size: 14px;
    margin-top: 10px;
    color: #999;
    display: flex;
    justify-content: space-between;
  }
}

.login-container {
  height: 100%;
}

.agreement {
  margin: 20px 20px;
  color: #999;
  font-size: 12px;

  .van-checkbox {
    justify-content: center;
    text-align: center;
  }

  .star-icon {
    width: 1em;
    height: 1em;
    padding: 0 5px;
  }
}

// 协议弹出
.popup-wrapper {
  padding: 16px;
  border-radius: 5px;

  .popup-content {
    text-align: center;
  }

  .popup-footer {
    display: flex;
    justify-content: space-evenly;
  }
}
</style>
